<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Question_model extends CI_Model {

    function __construct()
    {
        parent::__construct();
    }
	
    function get_question($email='',$siteid=''){
    	
    	$q = $this->db->get_where('sdk_question',array('email'=>$email,'siteid'=>$siteid));
    	
    	if($q->num_rows()>0){
    		
    		$res = $q->row();
    		
    		return $res->qid;
    		
    	}else{
    		
    		return false;
    	}
    	
    }
    
	function insert_question($question,$questioninfo){
		
		
		$this->db->trans_start();
		
		$this->db->insert('sdk_question',$question);
		$questioninfo['qid'] = $this->db->insert_id();
		$this->db->insert('sdk_questioninfo',$questioninfo);
		
		$this->db->trans_complete(); 
		
		return  ($this->db->trans_status() === FALSE) ? -1 : 0;		
	}
	
	function update_question($qid,$questioninfo){
	
	
		$this->db->trans_start();
		
		$this->db->update('sdk_question',array('status'=>0),array('qid'=>$qid));
		$this->db->insert('sdk_questioninfo',$questioninfo);
		
		$this->db->trans_complete(); 
		
		return  ($this->db->trans_status() === FALSE) ? -1 : 0;
	}
	
	function questionnumrows(){
	
		$q = $this->db->query("select * from sdk_question");
	
		return $q->num_rows();
	
	}
	
	function question_list($limit = 0,$size = 10){
		
		$sql = "select q.*,s.sitename,FROM_UNIXTIME(q.create_time, '%Y-%m-%d %H:%i') as ctime from sdk_question q join sdk_site s on q.siteid = s.siteid order by q.status , q.create_time desc limit ".$limit*$size.",".$size;
		
		$q = $this->db->query($sql);
		
		return $q->result();
	}
	
	function get_site_question_list($uid){

		$sql = "select i.* from sdk_questioninfo as i left join sdk_question as q on i.qid=q.qid where q.uid=$uid";
		$q = $this->db->query($sql);
		
		return $q->result();
	}
	
	function get_one_question($qid){
		$sql = "select q.*,m.firstname,m.lastname,m.email,s.sitename from sdk_question q left join sdk_member m on q.uid=m.mid left join sdk_site s on q.siteid=s.siteid where qid = '$qid'";
		$q = $this->db->query($sql);
		
		return $q->result();
	}
	
	function get_questioninfo($qid){
		
		$q = $this->db->get_where('sdk_questioninfo',array('qid'=>$qid));
		
		return $q->result();
	}
	
	function insert_answer($id,$qid,$answers){
		
		$this->db->trans_start();
		
		$this->db->update('sdk_questioninfo',array('answers'=>$answers),array('id'=>$id));
		
		$q = $this->db->get_where('sdk_questioninfo',array('qid'=>$qid,'answers'=>''));
		
		if($q->num_rows()==0) $this->db->update('sdk_question',array('status'=>1),array('qid'=>$qid));
		
		$this->db->trans_complete();
		
		return  ($this->db->trans_status() === FALSE) ? false : true;
	}
}